import hashlib
import random
import string
import time
import xml.etree.ElementTree as ET
from django.conf import settings
from django.utils import timezone
from wechatpy import WeChatPay

def get_wechat_pay_client():
    """获取微信支付客户端实例"""
    return WeChatPay(
        appid=settings.WECHAT_APP_ID,
        api_key=settings.WECHAT_PAY_API_KEY,
        mch_id=settings.WECHAT_PAY_MCH_ID,
        notify_url=settings.WECHAT_PAY_NOTIFY_URL,
        apiclient_cert_path=settings.WECHAT_PAY_CERT_PATH,
        apiclient_key_path=settings.WECHAT_PAY_KEY_PATH
    )

def generate_nonce_str():
    """生成随机字符串"""
    return ''.join(random.choices(string.ascii_letters + string.digits, k=32))

def generate_sign(data, api_key):
    """生成签名"""
    # 按字典序排序参数
    sorted_data = sorted([(k, v) for k, v in data.items() if k != 'sign' and v])
    # 拼接字符串
    stringA = '&'.join([f'{k}={v}' for k, v in sorted_data])
    # 拼接API密钥
    stringSignTemp = f'{stringA}&key={api_key}'
    # MD5加密并转大写
    sign = hashlib.md5(stringSignTemp.encode('utf-8')).hexdigest().upper()
    return sign

def dict_to_xml(data):
    """字典转XML"""
    xml = ['<xml>']
    for k, v in data.items():
        if isinstance(v, int):
            xml.append(f'<{k}>{v}</{k}>')
        else:
            xml.append(f'<{k}><![CDATA[{v}]]></{k}>')
    xml.append('</xml>')
    return ''.join(xml)

def xml_to_dict(xml_str):
    """XML转字典"""
    root = ET.fromstring(xml_str)
    data = {}
    for child in root:
        data[child.tag] = child.text
    return data